<?php

class LocationsController extends AppController {

    var $name = 'Locations';
    var $uses = array('Location');
    var $paginate = array(
        'Location' => array(
            'limit' => 10,
            'order' => array(
                'Location.id' => 'DESC'
            )
        )
    );

    /**
     * Location Model
     *
     * @var Location
     */
    var $Location;

    /**
     * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
     */
    function __initPublicActions() {
        $this->Auth->allow(array(
            'init_db'
        ));
    }

    function beforeFilter() {
        parent::beforeFilter();

        $this->__initPublicActions();
    }

    function init_db() {
        $this->loadModel('Group');

        $group = & $this->Group;

        //------------- root [id=1]
        $group->id = 1;

        $this->Acl->allow($group, 'controllers');
        //------------/ root [id=1]
        //------------- user [id=2]
        $group->id = 2;


        //------------/ user [id=2]

        echo "all done";
        exit;
    }

    function admin_index() {
        $this->Location->recursive = 0;
        $this->set('locations', $this->paginate('Location'));
    }

    function admin_add() {
        $this->Location->set($this->data);
        $this->Location->setValidation('admin_add');
        $fields_to_save = array('is_showempty', 'url_title', 'name', 'body', 'parent_id');

        if (!empty($this->data)) {
            $this->data["Location"] = $this->__trimData($this->data["Location"]);
            if ($this->Location->validates()) {
                $this->data["Location"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Location"]["name"], "UTF-8"), "-");

                $this->Location->create();
                if ($this->Location->save($this->data, true, $fields_to_save)) {
                    $this->Session->setFlash('Дестинацията е запаметена успешно');
                    $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
                } else {
                    $this->Session->setFlash('Грешка: The Location could not be saved. Please, try again.');
                }
            } else {
                $this->Session->setFlash('Грешка');
            }
        }

        $parents[0] = "[Root]";
        $locations = $this->Location->generatetreelist(null, null, null, '---');
        if ($locations) {
            foreach ($locations as $key => $value)
                $parents[$key] = $value;
        }
        $this->set(compact('parents'));

        $this->set('nextAutoIncrement', $this->Location->getNextAutoIncrement());
    }

    function admin_edit($id = null) {
        $this->Location->idFieldValue = $id;
        $this->Location->set($this->data);
        $this->Location->setValidation('admin_edit');
        $fields_to_save = array('is_active', 'is_showempty', 'url_title', 'name', 'body', 'parent_id');

        if (!$id && empty($this->data)) {
            $this->Session->setFlash('Невалидна дестинация');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
        }
        if (!empty($this->data)) {
            $this->data["Location"] = $this->__trimData($this->data["Location"]);

            if ($this->Location->validates()) {
                $this->data["Location"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Location"]["name"], "UTF-8"), "-");

                if ($this->Location->save($this->data, true, $fields_to_save)) {
                    $this->Session->setFlash('Дестинацията е запаметена успешно');
                    $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
                } else {
                    $this->Session->setFlash('Грешка: The Location could not be saved. Please, try again.');
                }
            } else {
                $this->Session->setFlash('Грешка');
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Location->read(null, $id);
        }

        $parents[0] = "[Root]";
        $locations = $this->Location->generatetreelist(null, null, null, '---');
        if ($locations) {
            foreach ($locations as $key => $value)
                $parents[$key] = $value;
        }
        $this->set(compact('parents'));
    }

    function admin_delete($id = null, $confirm = false) {
        if (!$id) {
            $this->Session->setFlash('Невалидна дестинация');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
        }

        $location = $this->Location->read(null, $id);
        $this->set('location', $location);

        if ($confirm) {
            if ($this->Location->delete($id)) {
                $this->Session->setFlash('Дестинацията е изтрита успешно');
                $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
            }

            $this->Session->setFlash('Грешка: The Location could not be deleted. Please, try again.');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
        }
    }

    function admin_addall() {
        $this->Location->setValidation('admin_addall');

        $isError = false;
        $savedLocations = array();

        if (!empty($this->data)) {
            $this->data["Location"] = $this->__trimData($this->data["Location"]);
            $allLocationsString = trim($this->data["Location"]["name"], " ,\t\n\r\0\x0B");

            $parent_id = $this->data['Location']['parent_id'];
            $conditions = array(
                'conditions' => array(
                    'or' => array(
                        "Location.id like" => "$parent_id"
                    )
                )
            );
            //$this->set('ListingsTags', $this->Listing->ListingTag->find('all', $conditions2)); 
            $result = $this->Location->find('all', $conditions);
            if (!empty($allLocationsString)) {

                unset($this->data["Location"]);

                $allLocationsExploded = explode(",", $allLocationsString);

                foreach ($allLocationsExploded as $currentLocationName) {
                     $currentLocationName = trim($currentLocationName, " ,\t\n\r\0\x0B");

                    $conditions = array(
                        'conditions' => array(
                            'or' => array(
                                "Location.name LIKE" => "$currentLocationName"
                            )
                        )
                    );
                    //$this->set('ListingsTags', $this->Listing->ListingTag->find('all', $conditions2)); 
                    $result2 = $this->Location->find('all', $conditions);

                    $currentLocationName = trim($currentLocationName, " ,\t\n\r\0\x0B");

                    if ($currentLocationName != "") {
                        if ($result2) {
                            $currentLocationName = $currentLocationName . ',' . $result[0]['Location']['name'];
                        }

                        $this->data["Location"]["name"] = $currentLocationName;
                        $this->data["Location"]["url_title"] = Inflector::slug(mb_strtolower($currentLocationName, "UTF-8"), "-");
                        $this->data['Location']['parent_id'] = $parent_id;

                        $this->Location->set($this->data);

                        if ($this->Location->validates()) {
                            $this->Location->create();
                            if (!$this->Location->save($this->data)) {
                                $isError = true;
                                $this->Session->setFlash('Грешка: The Location could not be saved. Please, try again.');
                                break;
                            } else {
                                $savedLocations[] = $currentLocationName;
                            }
                        } else {
                            $isError = true;
                            $this->Session->setFlash('Грешка');
                            break;
                        }
                    }
                }

                if (!$isError) {
                    $this->Session->setFlash('Дестинациите са запаметени успешно');
                    $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'locations', 'action' => 'index'));
                }
            }
        }

        $parents[0] = "[Root]";
        $locations = $this->Location->generatetreelist(null, null, null, '---');
        if ($locations) {
            foreach ($locations as $key => $value)
                $parents[$key] = $value;
        }
        $this->set(compact('parents'));


        $this->set('isError', $isError);
        $this->set('savedLocations', $savedLocations);
    }

}

?>